package org.mspring.mlog.service;

import org.mspring.mlog.cache.LinkCacheService;
import org.mspring.mlog.dao.LinkEntityDao;
import org.mspring.mlog.entity.LinkEntity;
import org.mspring.nbee.common.PageResult;
import org.mspring.nbee.db.dao.sql.builder.part.condition.SqlCondition;
import org.mspring.nbee.db.dao.sql.pager.SqlPager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author Gao Youbo
 * @since 2015-01-24 13:11:48
 */
@Service
public class LinkEntityService {

    private static final Logger LOG = LoggerFactory.getLogger(LinkEntityService.class);

    private LinkEntityDao linkEntityDao;
    private LinkCacheService linkCacheService;

    public LinkEntity findById(long id) {
        return linkEntityDao.findById(id);
    }

    public PageResult<LinkEntity> list(List<SqlCondition> conditions, SqlPager pager) {
        return linkEntityDao.listPage(conditions, pager);
    }

    public List<LinkEntity> listAll() {
        List<LinkEntity> linkList = linkCacheService.getLinkList();
        if (linkList == null) {
            linkList = linkEntityDao.listAll();
            linkCacheService.setLinkList(linkList);
        }
        return linkList;
    }

    @Transactional
    public boolean insert(LinkEntity link) {
        boolean flag = linkEntityDao.insert(link);
        if (flag) {
            linkCacheService.removeLinkList();
        }
        return flag;
    }

    @Transactional
    public boolean update(LinkEntity link) {
        boolean flag = linkEntityDao.update(link);
        if (flag) {
            linkCacheService.removeLinkList();
        }
        return flag;
    }

    @Transactional
    public boolean deleteById(long id) {
        boolean flag = linkEntityDao.deleteById(id);
        if (flag) {
            linkCacheService.removeLinkList();
        }
        return flag;
    }

    @Autowired
    public void setLinkEntityDao(LinkEntityDao linkEntityDao) {
        this.linkEntityDao = linkEntityDao;
    }

    @Autowired
    public void setLinkCacheService(LinkCacheService linkCacheService) {
        this.linkCacheService = linkCacheService;
    }
}